package logger.sd.server;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Servidor Multithread
 * 
 * @author Wendell
 */
public class MultithreadLoggingServer extends AbstractLoggingServer {

	private boolean threadpool;
	private int nThreads;
	private ExecutorService executor;

	/**
	 * Construtor do logger multithread
	 * 
	 * @param threadpool
	 *            Suporte a threadpool
	 */
	public MultithreadLoggingServer(ServerConfiguration config, boolean threadpool) {
		super(config);
		this.threadpool = threadpool;
		if (threadpool) {
			nThreads = config.getThreadPoolSize();
			System.out.println("Threadpool size: " + nThreads);
			executor = Executors.newFixedThreadPool(nThreads);
		}
		apresenta();
	}

	/**
	 * Apresenta os dados do servidor no prompt
	 */
	@Override
	protected void apresenta() {
		if (threadpool) {
			System.out.println("Iniciando servidor com threadpool.");
		} else {
			System.out.println("Instanciando servidor multithread");
		}
	}

	/**
	 * Delega o tratamento da requisicao criando uma nova Thread. 
	 * 
	 * @throws IOException
	 */
	@Override
	protected void trataRequisicao(Connection novaConexao) throws IOException {
		if (threadpool) {
			executor.execute(novaConexao);
		} else {
			Thread thread = new Thread(novaConexao);
			thread.start();
		}
	}
}
